package com.xxl.job.admin.utils;

import com.xxl.job.core.commons.exception.DataxException;
import com.xxl.job.core.commons.response.ReturnCode;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author xuyue
 * @email xuyue@cetcbigdata.com
 * @date 2021-4-21 9:49
 * 文件工具类
 */
public class FileUtils {
    public enum FileExt {
        PDF("pdf"), TXT("txt"),
        //office文件
        XLSX("xlsx"), XLS("xls"), DOC("doc"), DOCX("docx"), PPTX("pptx"),
        //图片文件
        JPG("jpg"), JPEG("jpeg"), BMP("bmp"), PNG("png"),
        //音频文件
        AMR("amr"), PCM("pcm"), WAV("wav"),
        //视频文件
        MP4("mp4"),
        //压缩文件
        TAR("tar"), ZIP("zip"), RAR("rar");
        private String ext;

        FileExt(String ext) {
            this.ext = ext;
        }

        public String getExt() {
            return this.ext;
        }
    }

    /**
     * @return 是否是压缩文件
     */
    public static boolean isCompressFile(File file) {
        String fileType = getFileExt(file);
        // 检测文件属性
        return (FileExt.TAR.getExt()).equals(fileType) ||
                (FileExt.ZIP.getExt()).equals(fileType) ||
                (FileExt.RAR.getExt()).equals(fileType);
    }

    /**
     * @return 是否是压缩文件
     */
    public static boolean isCompressFile(MultipartFile file) {
        String fileType = getFileExt(file);
        // 检测文件属性
        return (FileExt.TAR.getExt()).equals(fileType) ||
                (FileExt.ZIP.getExt()).equals(fileType) ||
                (FileExt.RAR.getExt()).equals(fileType);
    }

    /**
     * @return 文件扩展名（小写）
     */
    public static String getFileExt(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        int dot = fileName.lastIndexOf('.');
        if (dot > 0 && dot < fileName.length() - 1) {
            return fileName.substring(dot + 1).toLowerCase();
        } else {
            return "";
        }
    }

    /**
     * @return 文件扩展名（小写）
     */
    public static String getFileExt(File file) {
        String fileName = file.getName();
        int dot = fileName.lastIndexOf('.');
        if (dot > 0 && dot < fileName.length() - 1) {
            return fileName.substring(dot + 1).toLowerCase();
        } else {
            return "";
        }
    }

    /**
     * @param inputFile
     * @return File
     * @description MultipartFile 转 File 使用后必须删除文件
     */
    public static File multipartFileToFile(MultipartFile inputFile) {
        if (null == inputFile) {
            throw new DataxException("请传入文件参数", ReturnCode.INVALID_PARAMETER.getCode());
        }
        InputStream ins = null;
        try {
            ins = inputFile.getInputStream();
            File file = new File(inputFile.getOriginalFilename());
            org.apache.commons.io.FileUtils.copyToFile(ins, file);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (null != ins) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param files
     */
    public static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 删除文件目录及其下面的所有文件
     *
     * @param file
     */
    public static void deleteDirectory(File  file) {
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            for (File item : file.listFiles()) {
                deleteDirectory(item);
            }
        }
        file.delete();
    }

    /**
     * file转byte[]
     *
     * @param file
     */
    public static byte[] File2byte(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * description : InputStream转化为file
     *
     * @param ins
     * @param file
     * @author : tanxingsong
     * @date : 15:12 2019/3/8
     * @email : tanxingsong@cetcbigdata.com
     */
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
